#include <sys/select.h>
#include "timer.h"

static time_container tc = {0};

void check_timers(void);

void* timer_thread(void* param){
    struct timeval timeout = {0};
	while(1){
        timeout.tv_sec = 0;
        timeout.tv_usec = 50*1000;
		select(0,NULL,NULL,NULL,&timeout); 
		check_timers();
	}
	return NULL;
}

void check_timers(void){
	int32_t i;
	timer* pt;
	
	for(i = 0; i < Count_Timer_Max; i ++){
        pt = &tc.timers[i];
        if (pt->isStart){
            if (pt->time == 1){
                if (pt->timerFunction !=NULL)
                {
                    pt->timerFunction(pt->param);
                }
				if(pt->loop){
					pt->time = pt->interval;
				}
				else{
					pt->isStart = 0;
				}                
            }
            else pt->time--;
        }	
	}    
}

timer* timer_start(void (*timerFunction)(void * pointer), int32_t timeInterval,void* param,int loop)
{
	uint8_t i;
    timer* pt;
	for(i = 0; i < Count_Timer_Max; i ++)
	{
		if (tc.timers[i].isStart == 0)
		{
            pt = &tc.timers[i];
			pt->time = timeInterval;
			pt->interval = timeInterval;
			pt->timerFunction = timerFunction;
            pt->param = param;
			pt->loop = loop;
			tc.timers[i].isStart = 1;
			return pt;
		}
	}
	return 0;
}
int is_timer_started(timer* timer){
	return timer->isStart;
}

void exec_timer_func(timer* p_timer){
	p_timer->timerFunction(p_timer->param);
}

void timer_reset(timer* p_timer){
	if(p_timer){
		p_timer->time = p_timer->interval;
	}
}

void timer_stop(timer* timer) {
	if(timer){
		timer->isStart = 0;
	}
}
